package com.qf.java2007.web.controller;

import com.qf.java2007.pojo.Admin;
import com.qf.java2007.pojo.ReaderCard;
import com.qf.java2007.service.AdminService;
import com.qf.java2007.service.ReaderCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author AzureSky_X
 * @Date 2021/3/9 15:12
 * @Version 1.0
 */
@Controller
@Slf4j
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private ReaderCardService readerCardService;

    /**
     * 到登录界面
     *
     * @return
     */
    @GetMapping({"/", "/tologinui", "/login.html", "/login"})
    public String toLoginUI() {
        return "index";
    }

    /**
     * 登录检测
     *
     * @param id
     * @param passwd
     * @param session
     * @return
     */
    @PostMapping("/api/loginCheck")
    @ResponseBody
    public Map<String, String> loginCheck(String id, String passwd, HttpSession session) {
        log.info("id : {}", id);
        log.info("passwd : {}", passwd);

        Map<String, String> map = new HashMap<>();
        map.put("stateCode", "0");
        /**
         * 先进行管理员登录检测，
         * 若不是管理员再进行借阅人登录
         */
        //1 管理员登录
        try {
            Admin admin = adminService.login(id, passwd);
            session.setAttribute("admin", admin);
            map.put("stateCode", "1");
        } catch (Exception e) {
            e.printStackTrace();
            //管理员登录失败。
            //2 借阅人登录
            try {
                ReaderCard readerCard = readerCardService.login(id, passwd);
                session.setAttribute("readercard", readerCard);
                map.put("stateCode", "2");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return map;
    }

    /**
     * 用户登出
     *
     * @param session
     * @return
     */
    @GetMapping({"/logout", "/logout.html"})
    public ModelAndView logout(HttpSession session) {
        session.invalidate();
        ModelAndView mav = new ModelAndView("index");
        return mav;
    }

}
